package com.idea.zd.sys.train.thread.producerandconsumer;

import java.util.Date;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Producer implements Runnable{

    private Queue<String> product;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public Producer(Queue<String> product){
        this.product = product;
    }


    /*@Override
    public void run() {
        for (int i = 0; i < 4; i++) {
            try {
                lock.lock();
                while (product.size() > 0) {
                    condition.await();
                }

                product.add("生产者生产了一个产品：by" + new Date());
                condition.signal();

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

    }*/

    @Override
    public void run() {
        for (int i = 0; i < 4; i++) {
            synchronized (product){
                while (product.size() > 0) {
                    try {
                        product.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                product.add("生产者生产了一个产品：by" + new Date());
                product.notify();
            }
        }

    }
}